package com.itpeng.mobile;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itpeng.constant.MessageConstant;
import com.itpeng.constant.RedisMessageConstant;
import com.itpeng.entity.Result;
import com.itpeng.pojo.Member;
import com.itpeng.pojo.Order;
import com.itpeng.service.MemberService;
import com.itpeng.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.Map;

/**
 * @Aythor:彭彦钦
 * @Data: 2020/9/25  20:32
 */
@RestController
@RequestMapping("/order")
public class OrderMobileController {
    @Reference
    private OrderService orderService;

    @Autowired
    private JedisPool jedisPool;

    /**
     * 提交预约，并校验验证码
     * @param orderInfo
     * @return
     */
    @PostMapping("/submit")
    public Result submit(@RequestBody Map<String, String> orderInfo){
        String telephone= orderInfo.get("telephone");
        String key = RedisMessageConstant.SENDTYPE_ORDER + "_" + telephone;
        //1. 校验验证码
        //  获得jedis对象
        Jedis jedis = jedisPool.getResource();
        //  获得存储在redis中的验证码
        String codeInRedis = jedis.get(key);
        //  判断redis中是否有验证码
        if (StringUtils.isEmpty(codeInRedis)){
            return new Result(false, "验证码已超时或未发送，请重新获取验证码");
        }
        //  校验验证码
        String validateCode = orderInfo.get("validateCode");
        if (!codeInRedis.equals(validateCode)){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        jedis.del(key);
        //2. 验证码校验完毕，调用service层
        orderInfo.put("orderType", "微信预约");
        Order order = orderService.submitOrder(orderInfo);
        //3. 返回结果
        return new Result(true, MessageConstant.ORDER_SUCCESS,order);
    }

    /**
     * 根据ID得到预约信息
     * @param id
     * @return
     */
    @GetMapping("/findById")
    public Result findById(Integer id){
        Map<String, String> dataMap = orderService.findById(id);

        return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, dataMap);
    }

}
